package com.ftwj.utils.result;


import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 字符串校验工具类
 *
 * @author yoyx@foxmail.com
 * @date 2017年12月4日上午11:20:09
 */
public class StringTools {
    public static final String ALL_CHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final String NUM_CHAR = "0123456789";
    public static final Pattern p = Pattern.compile("<img[^>]*?src[\\s]*=[\\s]*(['|\"]{0,1})(.*?)\\1[^>]*?>", Pattern.CASE_INSENSITIVE);
    private static Random random = new Random();

    /**
     * 空字符串检测
     *
     * @param args
     * @return 是空串返回true
     * @author yoyx@foxmail.com
     * @version 创建时间：2017年12月4日上午11:20:09
     */
    public static boolean isNullStr(String... args) {
        boolean falg = false;
        for (String arg : args) {
            if (StringUtils.isEmpty(arg) || arg.equals("null") || arg == null || "".equals(arg)) {
                falg = true;
                return falg;
            }
        }
        return falg;
    }

    /**
     * 判断是不是有不为空的字符串 只要有一个字符串不为空就返回true
     *
     * @param args
     * @return
     * @author yoyx@foxmail.com
     * @version 创建时间：2017年12月4日上午11:20:09
     */
    public static boolean isNotAllNullStr(String... args) {
        boolean falg = true;
        for (String arg : args) {
            if (!StringUtils.isEmpty(arg)) {
                falg = false;
                return falg;
            }
        }
        return falg;
    }

    /**
     * @author: jaymou@qq.com
     * @Description: 返回一个定长的随机字符串(只包含大小写字母 、 数字)
     */
    public static String generateString(int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append(ALL_CHAR.charAt(random.nextInt(ALL_CHAR.length())));
        }
        return sb.toString();
    }

    public static String generateNumString(int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append(ALL_CHAR.charAt(random.nextInt(NUM_CHAR.length())));
        }
        return sb.toString();
    }

    /**
     * @author: jaymou@qq.com
     * @Description: 将Object转换为String
     */
    @SuppressWarnings("unused")
    public static String objectToString(Object object) {
        if (object != null) {
            return object + "";
        } else {
            return "";
        }
    }


    /**
     * @Description: 获取JSONObject对象
     * @author jaymou@qq.com
     */
    public static String getJsonObjectString(com.alibaba.fastjson.JSONObject jsonObject, String key) {
        if (jsonObject.containsKey(key)) {
            String string = jsonObject.getString(key);
            string = "null".equals(string) ? null : string;
            return string;
        }
        return "";
    }

    /**
     * @Description: TODO：(拼接in字符串)
     * @author: jaymou@qq.com
     */
    public static String getInWord(String orignStr) {
        String[] projectArr = orignStr.split(",");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < projectArr.length; i++) {
            sb.append("'" + projectArr[i] + "'");//拼接单引号,到数据库后台用in查询. 
            if (i != projectArr.length - 1) {//前面的元素后面全拼上",",最后一个元素后不拼 
                sb.append(",");
            }
        }
        return sb.toString();
    }

    public static String getListInWord(List<Map<String, Object>> list) {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append("'" + list.get(i).get("id") + "'");//拼接单引号,到数据库后台用in查询. 
            if (i != list.size() - 1) {//前面的元素后面全拼上",",最后一个元素后不拼 
                sb.append(",");
            }
        }
        return sb.toString();
    }

    /**
     * 获取文件前缀
     *
     * @param fileName
     * @return
     */
    public static String getFilePrefix(String fileName) {
        if (fileName == null || "".equals(fileName)) {
            return null;
        }
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    /**
     * 获取文件后缀
     *
     * @param fileName
     * @return
     */
    public static String getFileSufix(String fileName) {
        int pointIndex = fileName.lastIndexOf(".");
        if (fileName == null || "".equals(fileName) || pointIndex < 0) {
            return null;
        }
        return fileName.substring(pointIndex);//从最后一个点之后截取字符串
    }

    /**
     * @description: 获取项目路径
     * @author: JayMou
     * @time: 2019/7/18 10:26
     */

    public static String getWebAppPath(HttpServletRequest request) {
        String path = "";
        String protol = request.getScheme();//获取协议，http
        String serverName = request.getServerName();//获取服务器名，localhost
        int serverPort = request.getServerPort();//获取服务器端口，8080
        String contextPath = request.getContextPath();//获取项目名，/DemoName
        path = new StringBuffer(protol).append("://").append(serverName).append(":").append(serverPort).append(contextPath).toString();
        return path;
    }


    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * <p>
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
     * <p>
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130,
     * 192.168.1.100
     * <p>
     * 用户真实IP为： 192.168.1.110
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String filterNull(String str) {
        str = "" + str;
        if ("null".equals(str.trim())) {
            str = "";
        }
        return str;
    }

    /**
     * 处理父子级管理列表数据
     *
     * @return
     */
    public static List<Map<String, Object>> sortFcList(List<Map<String, Object>> list) {
        List<Map<String, Object>> faterList = new ArrayList<Map<String, Object>>();
        if (list != null && !list.isEmpty()) {
            for (Map<String, Object> map : list) {
                String fid = filterNull("" + map.get("fid"));
                if ("0".equals(fid)) {
                    faterList.add(map);
                }
            }

            for (Map<String, Object> fatherMap : faterList) {
                String id = filterNull("" + fatherMap.get("id"));
                List<Map<String, Object>> childList = new ArrayList<Map<String, Object>>();
                for (Map<String, Object> map : list) {
                    String fid = filterNull("" + map.get("fid"));
                    if (id.equals(fid)) {
                        childList.add(map);
                    }
                }
                fatherMap.put("childList", childList);
            }
        }
        return faterList;
    }

    /**
     * 8 位 UCS 转换格式
     */
    public static final String UTF_8 = "UTF-8";

    /**
     * 将字符编码转换成UTF-8码
     */
    public static String toUTF_8(String str) {
        return changeCharset(str, UTF_8);
    }

    /**
     * 字符串编码转换的实现方法
     *
     * @param str        待转换编码的字符串
     * @param oldCharset 原编码
     * @param newCharset 目标编码
     * @return
     * @throws UnsupportedEncodingException
     */
    public String changeCharset(String str, String oldCharset, String newCharset) {
        try {
            if (str != null) {
                //用旧的字符编码解码字符串。解码可能会出现异常。  
                byte[] bs = str.getBytes(oldCharset);
                //用新的字符编码生成字符串  
                return new String(bs, newCharset);
            }
        } catch (UnsupportedEncodingException e) {
            System.err.println("解码异常，不能处理");
        }
        return null;
    }

    /**
     * @param str        待转换编码的字符串
     * @param newCharset 目标编码
     * @return
     * @throws UnsupportedEncodingException
     * @描述:* 字符串编码转换的实现方法
     * @Author: jaymou@qq.com
     */
    public static String changeCharset(String str, String newCharset) {
        try {
            if (str != null) {
                //用默认字符编码解码字符串。  
                byte[] bs = str.getBytes();
                //用新的字符编码生成字符串  
                return new String(bs, newCharset);
            }
        } catch (UnsupportedEncodingException e) {
        }
        return null;
    }

    /**
     * @param content
     * @param prefix
     * @return
     * @描述:替换富文本
     * @Author: jaymou@qq.com
     */
    public static String replaceRomtePath(String content, String prefix) {
        if (content == null) {
            return null;
        }

        Matcher m = p.matcher(content);
        while (m.find()) {
            String path = m.group(2);
            if (path != null && !(path.trim().toLowerCase().startsWith("http://"))) {
                content = content.replace(path, prefix + path);
            }
        }
        return content;
    }

    //移动
    public static final String MOBILE = "mobile";
    //电信
    public static final String TELECOM = "telecom";
    //联通
    public static final String UNICOM = "unicom";

    /**
     * @author Liu_xg
     * @date 2022-7-5 11:21
     * @description: 根据号码判断运营商
     */
    public static String getPhoneOperator(String phone) {
        if (StringTools.isNullStr(phone)) {
            return TELECOM;
        }
        String operator = "";
        String isMoblie = "((13[4-9])|147|(15[0-2])|(15[7-9])|(17[2,8])|(18[2-4])|(18[7-8])|(19[5,7,8]))\\d{8}";
        String isUnicom = "((13[0-2])|(14[0,5,6])|(15[5-6])|166|(17[5,6])|(18[5-6])|196)\\d{8}";
        if (phone.matches(isMoblie)) {
            //System.out.println("这是一个移动的号码");
            operator = MOBILE;
        } else if (phone.matches(isUnicom)) {
            //System.out.println("这是一个联通的号码");
            operator = UNICOM;
        } else {
            //System.out.println("这是一个电信的号码");
            operator = TELECOM;
        }
        return operator;
    }


}
